/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mobileAPI;

import entity.Courserates;
import entity.Courses;
import entity.Coursetag;
import entity.Enrollment;
import entity.Lecture;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpa.controllers.CoursesJpaController;
import jpa.controllers.EnrollmentJpaController;
import net.sf.json.JSONObject;

/**
 *
 * @author Geymen
 */
@WebServlet(name = "CourseDetailServlet", urlPatterns = {"/mobile/coursedetail"})
public class CourseDetailServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        Integer userID;
        userID = Integer.valueOf(request.getParameter("userID"));
        
        Integer courseID;
        courseID = Integer.valueOf(request.getParameter("courseID"));
        
        // First generate a map object for keeping keys and values.
        Map courseDetailMap = new HashMap();
        
        //********************************
        
        // Second get user related details
        EnrollmentJpaController enrollmentJpaController = new EnrollmentJpaController();
        Enrollment enrollment = enrollmentJpaController.findEnrollment(userID, courseID);
        
        if (enrollment != null) {
            courseDetailMap.put("userEnrolled", Boolean.TRUE);
            Courserates courseRate = enrollment.getCourserates();
            
            if (courseRate != null) {
                courseDetailMap.put("userRated", Boolean.TRUE);
                courseDetailMap.put("userRatePoint", new Integer(courseRate.getPoints()));
            } else {
                courseDetailMap.put("userRated", Boolean.FALSE);
                courseDetailMap.put("userRatePoint", new Integer(-1));
            }
            
        } else {
            courseDetailMap.put("userEnrolled", Boolean.FALSE);
            courseDetailMap.put("userRated", Boolean.FALSE);
            courseDetailMap.put("userRatePoint", new Integer(-1));
        }
        
        //********************************
        
        // Third get basic course details
        CoursesJpaController coursesJpaController = new CoursesJpaController();
        Courses course = coursesJpaController.findCourses(courseID);
        
        courseDetailMap.put("courseID", new Integer(courseID));
        courseDetailMap.put("courseName", new String(course.getName()));
        courseDetailMap.put("courseDescription", new String(course.getDescription()));
        courseDetailMap.put("courseCreatorName", new String(course.getCreaterUserId().getName()));
        
        //********************************
        
        // Forth get rating
        List<Enrollment> enrollmentList = enrollmentJpaController.findEnrollmentEntitiesWithCourseID(courseID);
        List<Courserates> courseRatesList = new ArrayList<Courserates>();
        for (Iterator<Enrollment> it = enrollmentList.iterator(); it.hasNext();) {
            Enrollment tempEnrollment = it.next();
            if (tempEnrollment.getCourserates() != null) {
                courseRatesList.add(tempEnrollment.getCourserates());
            }
        }
        
        Float totalRating = 0.f;
        for (Iterator<Courserates> it = courseRatesList.iterator(); it.hasNext();) {
            Courserates tempCourseRate = it.next();
            totalRating += tempCourseRate.getPoints().floatValue();
        }
        if (!courseRatesList.isEmpty()) {
            totalRating /= courseRatesList.size();
        }
        
        courseDetailMap.put("courseRating", new Float(totalRating.floatValue()));
        
        //********************************
        
        // Fifth get course tags
        List<Coursetag> courseTagList = course.getCoursetagList();
        ArrayList tagMapList = new ArrayList();
        for (Iterator<Coursetag> it = courseTagList.iterator(); it.hasNext();) {
            Coursetag coursetag = it.next();
            
            Map courseTagMap = new HashMap();
            courseTagMap.put("tagID", new Integer(coursetag.getTagId().getId()));
            courseTagMap.put("tagName", new String(coursetag.getTagId().getTagName()));
            tagMapList.add(courseTagMap);
        }
        
        courseDetailMap.put("courseTags", tagMapList);
        
        //********************************
        
        //Sixth get lecture list
        List<Lecture> lectureList = course.getLectureList();
        ArrayList lectureMapList = new ArrayList();
        for (Iterator<Lecture> it = lectureList.iterator(); it.hasNext();) {
            Lecture lecture = it.next();
            
            Map lectureMap = new HashMap();
            lectureMap.put("lectureID", new Integer(lecture.getId()));
            lectureMap.put("lectureName", new String(lecture.getLectureName()));
            lectureMap.put("lectureLink", new String(lecture.getLink()));
            lectureMapList.add(lectureMap);
        }
        
        courseDetailMap.put("courseLectures", lectureMapList);
        
        //********************************
        
        JSONObject respondJSONObject = JSONObject.fromObject(courseDetailMap);
        
        try {
            /* TODO output your page here. You may use following sample code. */
//            out.println("<!DOCTYPE html>");
//            out.println("<html>");
//            out.println("<head>");
//            out.println("<title>Servlet CourseDetailServlet</title>");            
//            out.println("</head>");
//            out.println("<body>");
//            out.println("<h1>Servlet CourseDetailServlet at " + request.getContextPath() + "</h1>");
//            out.println("</body>");
//            out.println("</html>");
            
            out.println(respondJSONObject);
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
